Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Runtime.InteropServices
Imports System.Configuration
Imports System.Text
Public Class UserManagement
    Private x As String
    Public pintype As String
    Public pinlength As String
    Public SESSION_USER_ID As String
    Public SESSION_VIAKLIX_ID As String
    Public SESSION_COMPANY_ID As Integer
    Private EventID As Integer
    Public nPage As Long
    Public nNumPages As Integer
    Public nPageRecords As Integer
    Public Password As String
    Public OrigPassword As String
    Public FirstNameOld As String
    Public FirstName As String
    Public LastNameOld As String
    Public LastName As String
    Public LocationOld As String
    Public Location As String
    Public PhoneOld As String
    Public Phone As String
    Public extOld As String
    Public ext As String
    Public supervisorOld As String
    Public Supervisor As String
    Public ActiveOld As String
    Public Active As String
    Public EmailOld As String
    Public Email As String
    Public RoleIDOld As Integer
    Public RoleID As Integer
    Public nTermCnt As Integer
    Public isELevelUser As Boolean

    Public SessionID As String

    'Private oAudit As viaAudit.AuditEvent
    Private oAudit As Object
    Public DBConnectstring As String
    Public ServerIP As String
    Public ServerTime As String
    Public SourceIP As String

    Public ErrMsg As String

    Public Function AddUser(ByVal UID As String, _
            ByVal VID As String, _
            ByVal CID As Integer, _
            ByVal Password As String, _
            ByVal FirstName As String, _
            ByVal LastName As String, _
            ByVal Location As String, _
            ByVal Phone As String, _
            ByVal Email As String, _
            ByVal Supervisor As String, _
            ByVal Active As String) As String

        Dim sSQL As String
        Dim vAchar As Object
        Dim vAnum As Object
        Dim validpwd2 As Integer
        Dim validpwd1 As Integer
        Dim valid1 As Boolean
        Dim valid2 As Boolean
        Dim i As Integer
        Dim a As Integer
        Dim Conn As SqlConnection
        Dim Rs As DataSet
        Dim Rs1 As DataSet = Nothing
        Dim bExistingUser As Boolean
        Dim bAdduserOk As Boolean
        Dim sErr As String = ""
        Conn = New SqlConnection
        Dim Cmd As SqlCommand
        'Set Rs = New ADODB.Recordset
        'Conn.Open(DBConnectstring)
        'Rs.ActiveConnection = Conn
        'Rs.CursorLocation = adUseClient
        If SESSION_VIAKLIX_ID = "000000" Then
            If Supervisor <> "" And Len(Supervisor) > 0 Then
                Rs = New DataSet

                sSQL = "SELECT * FROM USERS"
                sSQL = sSQL & " WHERE User_ID = " & CheckString(Supervisor) & " "
                sSQL = sSQL & " and viaKlix_ID = " & CheckString(VID) & " "
                sSQL = sSQL & " and Company_ID = " & CID

                GetDataset(DBConnectstring, sSQL, "users", sErr, Rs)
                If Rs.Tables(0).Rows.Count = 0 Then
                    sErr = "This supervisor does not exist."
                    AddUser = sErr
                    Exit Function
                End If

            End If
        End If
        sSQL = "SELECT * FROM USERS"
        sSQL = sSQL & " WHERE User_ID = " & CheckString(UID) & " "
        sSQL = sSQL & " and viaKlix_ID = " & CheckString(VID) & " "
        sSQL = sSQL & " and Company_ID = " & CID

        GetDataset(DBConnectstring, sSQL, "users", sErr, Rs1)
        If Rs1.Tables(0).Rows.Count > 0 Then
            sErr = "User account already exists."
            bExistingUser = True
            AddUser = sErr
            Exit Function
        End If
        If Not bExistingUser Then
            If Password <> "" Then
                vAchar = Split("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,!,@,#,$,%,^,&,*,(),_,-,=,+,<,>,?,/,:,;,',[,],{,},|,\,`,~", ",")
                vAnum = Split("1,2,3,4,5,6,7,8,9,0", ",")

                If Len(Password) < 6 Then
                    sErr = "Please enter a minimum of six(6) characters. Your password must contain at least one letter and one number."
                    AddUser = sErr
                    Exit Function
                Else

                    For i = 0 To UBound(vAchar)
                        validpwd1 = InStr(1, Password, vAchar(i), vbTextCompare)
                        If CLng(validpwd1) > 0 Then
                            valid1 = True
                            Exit For
                        End If
                    Next

                    If valid1 Then
                        For a = 0 To UBound(vAnum)
                            validpwd2 = InStr(Password, vAnum(a))
                            If CLng(validpwd2) > 0 Then
                                valid2 = True
                                Exit For
                            End If
                        Next
                        If Not valid2 Then
                            sErr = "Your password must contain at least one number."
                            AddUser = sErr
                            Exit Function
                        End If
                    Else
                        If Not valid1 Then
                            sErr = "Your password must contain at least one letter."
                            AddUser = sErr
                            Exit Function
                        End If
                    End If

                End If
            End If

            '=====
            Cmd = New SqlCommand
            With Cmd
                .Connection = Conn
                .CommandType = CommandType.StoredProcedure
                Cmd.CommandText = "VIAKLIX_PROCESSING.INSUSER"
                .Parameters.Add(New SqlParameter("@i_userID", SqlDbType.VarChar, 15)).Value = UID
                .Parameters.Add(New SqlParameter("@i_viaklixid", SqlDbType.VarChar, 15)).Value = VID
                .Parameters.Add(New SqlParameter("@i_companyid", SqlDbType.VarChar, 5)).Value = CInt(CID)
                .Parameters.Add(New SqlParameter("@i_password", SqlDbType.VarChar, 15)).Value = Password
                .Parameters.Add(New SqlParameter("@i_roleid", SqlDbType.Int, 5)).Value = 1
                .Parameters.Add(New SqlParameter("@i_firstname", SqlDbType.VarChar, 20)).Value = FirstName
                .Parameters.Add(New SqlParameter("@i_lastname", SqlDbType.VarChar, 30)).Value = LastName
                .Parameters.Add(New SqlParameter("@i_location", SqlDbType.VarChar, 50)).Value = Location
                .Parameters.Add(New SqlParameter("@i_phone", SqlDbType.VarChar, 20)).Value = Phone
                .Parameters.Add(New SqlParameter("@i_ext", SqlDbType.VarChar, 10)).Value = ext
                .Parameters.Add(New SqlParameter("@i_emailaddress", SqlDbType.VarChar, 255)).Value = Email
                .Parameters.Add(New SqlParameter("@i_supervisor", SqlDbType.VarChar, 15)).Value = Supervisor
                .Parameters.Add(New SqlParameter("@i_active", SqlDbType.VarChar, 1)).Value = Active
                .Parameters.Add(New SqlParameter("@0_errormsg", SqlDbType.VarChar, 255)).Direction = ParameterDirection.Output
            End With
            Try

                Cmd.Connection.Open()
                Cmd.ExecuteNonQuery()
                '------------------------------------------------------------------------
                'Returns a message to the calling ASP page.
                '------------------------------------------------------------------------
                If Not IsNothing(Cmd.Parameters("0_errormsg").Value) Then

                    'Debug.Print("Error Msg = " & Cmd.Parameters("0_errormsg" 
                    ErrMsg = Cmd.Parameters("0_errormsg").Value


                End If
                '------------------------------------------------------------------------
            Catch ex As SqlException
                'Dim strErrEx As String = ""
                'Dim strTDErr As String
                'Dim i As Integer = 0

                For i = 0 To ex.Errors.Count - 1
                    ErrMsg = ex.Errors(i).Message.ToString()
                Next i
                ''/**use this code to debug**//

                LogErrorEvent(ErrMsg)

            Finally
                If Not (Conn Is Nothing) Then
                    Conn.Close()
                End If
            End Try

            bAdduserOk = True
            'Cmd = Nothing
            'Conn.Close()
            'Conn = Nothing
            'oAudit = New gaAugit.AuditEvent 'CreateObject("viaAudit.AuditEvent")
            oAudit.DBConnectstring = DBConnectstring
            oAudit.SESSION_USER_ID = SESSION_USER_ID
            oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
            oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
            oAudit.AFFECTED_USER_ID = UID
            oAudit.AFFECTED_VIAKLIX_ID = VID
            oAudit.AFFECTED_COMPANY_ID = CInt(CID)
            oAudit.AddInfo(68, ServerIP)
            oAudit.AddInfo(69, ServerTime)
            oAudit.AddInfo(70, SourceIP)
            oAudit.EventID = 8  '-----  User Creation
            x = oAudit.SaveEvent()
            oAudit = Nothing
            'End If
            AddUser = "OK"
            Exit Function
        End If
        'ErrorHandler:
        '        Call LogErrorEvent(".AddUser")

        '        If Not Rs Is Nothing Then
        '            If Rs.State <> adStateClosed Then
        '                Rs.Close()
        '            End If

        '            Rs = Nothing
        '        End If

        '        If Not Conn Is Nothing Then
        '            If Conn.State <> adStateClosed Then
        '                Conn.Close()
        '            End If

        '            Conn = Nothing
        '        End If

        '        oAudit = Nothing
        '        Cmd = Nothing
        Return Nothing
    End Function

    Public Function AdduserConfirm(ByVal UID As String, ByVal VID As String, ByVal CID As String) As DataSet

        Dim sSQL As String = ""
        Dim sErr As String = ""
        'Dim bUserExit As Boolean=

        Dim Rs As DataSet

        sSQL = "SELECT "
        sSQL = sSQL & " r.Company_name,  "
        sSQL = sSQL & " u.USER_ID, "
        sSQL = sSQL & " u.VIAKLIX_ID, "
        sSQL = sSQL & " u.COMPANY_ID, "
        sSQL = sSQL & " u.PASSWORD,   "
        sSQL = sSQL & " u.ROLEID, "
        sSQL = sSQL & " u.FIRST_NAME, "
        sSQL = sSQL & " u.LAST_NAME,  "
        sSQL = sSQL & " u.LOCATION,   "
        sSQL = sSQL & " u.PHONE,  "
        sSQL = sSQL & " u.EXT,    "
        sSQL = sSQL & " u.EMAIL_ADDRESS,  "
        sSQL = sSQL & " u.SUPERVISOR, "
        sSQL = sSQL & " u.Active "
        sSQL = sSQL & "FROM "
        sSQL = sSQL & "   rebrand_companies r, users u "
        sSQL = sSQL & "WHERE "
        sSQL = sSQL & "   u.Company_ID = r.Company_ID "
        sSQL = sSQL & " and u.User_ID=" & CheckString(UID) & " AND u.Company_ID = " & CInt(CID) & " AND u.Viaklix_ID =" & CheckString(VID)

        'sSQL = "SELECT * FROM USERS u, REBAND_COMPANIES r "
        'sSQL = sSQL & " WHERE User_ID=" & CheckString(UID) & " AND Company_ID = " & CInt(CID) & " AND Viaklix_ID =" & CheckString(VID)
        Rs = New DataSet
        Try
            GetDataset(DBConnectstring, sSQL, "users", sErr, Rs)
            'Rs.Open(sSQL, Conn, adOpenForwardOnly, adLockReadOnly, adCmdText)

            If Rs.Tables(0).Rows.Count > 0 Then
                AdduserConfirm = Rs
                'Rs.ActiveConnection = Nothing
                'Conn.Close()
                'Conn = Nothing
                Exit Function
            End If
        Catch ex As SqlException
            'Dim strErrEx As String = ""
            'Dim strTDErr As String
            Dim i As Integer = 0

            For i = 0 To ex.Errors.Count - 1
                sErr = ex.Errors(i).Message.ToString()
            Next i
            ''/**use this code to debug**//

            LogErrorEvent(sErr)


        End Try

        Return Nothing
    End Function

    Public Function GetMerchantUsers(ByVal sVID As String, Optional ByVal sSupervisor As String = "") As Array

        Dim sSQL As String
        Dim vUserlist As Object
        Dim Rs As DataSet
        Dim aUsers As Object
        'Dim nIndexLoc As Integer
        'Dim bRet As Boolean
        Dim i As Integer
        Dim j As Integer
        Dim sErr As String = ""
        Rs = New DataSet

        sSQL = "SELECT User_ID, "
        sSQL = sSQL & "NVL(Supervisor,'" & sVID & "') as supervisor, "
        sSQL = sSQL & "Active FROM USERS where company_id = 1 "
        sSQL = sSQL & "and VIAKLIX_ID = '" & sVID & "' "
        sSQL = sSQL & "ORDER BY supervisor, User_ID"
        GetDataset(DBConnectstring, sSQL, "users", sErr, Rs)
        'Rs.Open(sSQL, Conn, adOpenStatic, adLockReadOnly, adCmdText)
        If Rs.Tables(0).Rows.Count > 0 Then
            'Create and populate a column-based array (vUserlist) using the recordset results
            vUserlist = Rs
            'Redimension a row-based array (aSortedUsers) using the size of the column-based array (vUserlist).
            'aSortedUsers contains an additional column that will store a user level indicator.
            ReDim aUsers(UBound(vUserlist, 2), UBound(vUserlist) + 1)

            'Populate the row-based array using vUserlist's data
            For i = 0 To UBound(vUserlist, 2)
                For j = 0 To UBound(vUserlist)
                    aUsers(i, j) = vUserlist(j, i)
                Next
            Next

            SortUsers(aUsers, sVID)

            'Setting the user level indicator for root and supervisors
            For i = 0 To UBound(aUsers)
                For j = 0 To UBound(aUsers, 2)
                    Select Case SafeString(aUsers(i, 1))
                        Case sVID
                            aUsers(i, 3) = 1
                        Case ""
                            aUsers(i, 3) = 0
                    End Select

                    If aUsers(i, 0) = aUsers(i, 1) Then
                        aUsers(i, 3) = 0
                    End If
                Next

                If aUsers(i, 3) > 0 Then
                    'Setting the user level indicator for supervisor subordinates
                    'SetUserLevel(aUsers, aUsers(i, 0), aUsers(i, 3))
                End If
            Next

        End If
        'Conn.Close()
        'Conn = Nothing

        'For i = 0 To UBound(aUsers)
        '    For j = 0 To UBound(aUsers, 2)
        '        Debug.Print ("i = " & i & " j = " & j & " value = " & aUsers(i, j 
        '    Next
        'Next

        ' GetMerchantUsers = aUsers

        'ErrorHandler:
        '        Call LogErrorEvent(".GetMerchantUsers")

        '        If Not Rs Is Nothing Then
        '            If Rs.State <> adStateClosed Then
        '                Rs.Close()
        '            End If

        '            Rs = Nothing
        '        End If

        '        If Not Conn Is Nothing Then
        '            If Conn.State <> adStateClosed Then
        '                Conn.Close()
        '            End If

        '            Conn = Nothing
        '        End If
        Return Nothing
    End Function
    'Private Function SetUserLevel(ByRef aUsers, ByVal Manager, ByVal UserLevel)
    '    Dim i As Integer

    '    For i = 0 To UBound(aUsers)
    '        If aUsers(i, 1) = Manager Then
    '            aUsers(i, 3) = UserLevel + 1
    '        End If
    '    Next
    'End Function
    Private Sub SortUsers(ByRef aUsers, ByVal Supervisor)
        Dim indx1 As Integer
        Dim indx2 As Integer
        Dim aUnsortedUsers As Object

        aUnsortedUsers = aUsers
        indx2 = 0

        For indx1 = 0 To UBound(aUnsortedUsers)
            If aUnsortedUsers(indx1, 0) = aUnsortedUsers(indx1, 1) Then
                aUsers(indx2, 0) = aUnsortedUsers(indx1, 0)
                aUsers(indx2, 1) = ""
                aUsers(indx2, 2) = aUnsortedUsers(indx1, 2)
                aUsers(indx2, 3) = aUnsortedUsers(indx1, 3)
                indx2 = indx2 + 1
            ElseIf aUnsortedUsers(indx1, 1) = Supervisor Then
                aUsers(indx2, 0) = aUnsortedUsers(indx1, 0)
                aUsers(indx2, 1) = aUnsortedUsers(indx1, 1)
                aUsers(indx2, 2) = aUnsortedUsers(indx1, 2)
                aUsers(indx2, 3) = aUnsortedUsers(indx1, 3)
                indx2 = indx2 + 1
                FindSubordinates(aUnsortedUsers, aUsers, aUnsortedUsers(indx1, 0), indx2)
            End If
        Next

    End Sub
    Private Sub FindSubordinates(ByVal aUnsortedUsers, ByRef aUsers, ByVal Manager, ByRef indx2)
        Dim indx1 As Integer
        For indx1 = 0 To UBound(aUnsortedUsers)
            If aUnsortedUsers(indx1, 1) = Manager Then
                aUsers(indx2, 0) = aUnsortedUsers(indx1, 0)
                aUsers(indx2, 1) = aUnsortedUsers(indx1, 1)
                aUsers(indx2, 2) = aUnsortedUsers(indx1, 2)
                aUsers(indx2, 3) = aUnsortedUsers(indx1, 3)
                indx2 = indx2 + 1
                FindSubordinates(aUnsortedUsers, aUsers, aUnsortedUsers(indx1, 0), indx2)
            End If
        Next
    End Sub

    Public Function FindUsers(ByVal UID As String, _
            ByVal CID As Integer, _
            ByVal VID As String, _
            ByVal LastName As String, _
            ByVal FirstName As String, _
            ByVal Location As String, _
            ByVal sortby As String, _
            ByVal ToggleSortOrder As Boolean) As Object
        'On Error GoTo ErrorHandler
        Dim sSQL As String
        'Dim vUserlist As DataSet
        'Dim Conn As ADODB.Connection
        'Dim Rs As ADODB.Recordset
        Dim SortOrder As String = ""
        'Conn = New ADODB.Connection
        Dim Rs As DataSet = Nothing
        Dim sErr As String = ""
        Dim nPagesize As Integer

        'SaveSortField(sortby, SortOrder, ToggleSortOrder)

        sSQL = "SELECT "
        sSQL = sSQL & "   r.Company_name, "
        sSQL = sSQL & "   u.User_ID, "
        sSQL = sSQL & "   u.Company_ID, "
        sSQL = sSQL & "   u.viaklix_ID, "
        sSQL = sSQL & "   u.First_name, "
        sSQL = sSQL & "   u.Last_name, "
        sSQL = sSQL & "   u.Location, "
        sSQL = sSQL & "   u.Supervisor, "
        sSQL = sSQL & "   u.Active "
        sSQL = sSQL & "FROM "
        sSQL = sSQL & "   rebrand_companies r, users u "
        sSQL = sSQL & "WHERE "
        sSQL = sSQL & "   u.Company_ID = r.Company_ID "

        If UID <> "" Then
            sSQL = sSQL & " AND Upper(u.USER_Id) like '%" & UCase(UID) & "%'"
        End If

        If CID > -1 Then
            sSQL = sSQL & " AND u.Company_ID = " & CID & " "
        End If

        If VID <> "" Then
            sSQL = sSQL & " AND u.viaklix_Id like '%" & VID & "%'"
        End If

        If LastName <> "" Then
            sSQL = sSQL & " AND Upper(u.last_name) like '%" & UCase(LastName) & "%'"
        End If

        If FirstName <> "" Then
            sSQL = sSQL & " AND Upper(u.first_name) like '%" & UCase(FirstName) & "%'"
        End If
        If Location <> "" Then
            sSQL = sSQL & " AND Upper(u.location) like '%" & UCase(Location) & "%'"
        End If
        If isELevelUser Then
            sSQL = sSQL & " AND user_id IN "
            sSQL = sSQL & " ( "
            sSQL = sSQL & " select user_id from (select * from users where Upper(viaklix_Id) like "
            sSQL = sSQL & "'%" & UCase(VID) & "%') START WITH supervisor = (SELECT SUPERVISOR "
            sSQL = sSQL & "From users "
            sSQL = sSQL & "WHERE company_id = " & CID & " AND"
            sSQL = sSQL & "      viaklix_id ='" & SESSION_VIAKLIX_ID & "' And "
            sSQL = sSQL & "            user_id = '" & SESSION_USER_ID & "')"
            sSQL = sSQL & " CONNECT BY supervisor = prior user_id)"
        End If

        If sortby <> "" Then

            Select Case sortby
                Case "UID"
                    sortby = "u.User_id"
                Case "LASTNAME"
                    sortby = "u.last_name"
                Case "FIRSTNAME"
                    sortby = "u.First_name"
                Case "LOCATION"
                    sortby = "u.Location"
                Case "SUPVISOR"
                    sortby = "Supervisor"
                Case "ACTIVE"
                    sortby = "Active"
                Case "VID"
                    sortby = "viaklix_ID"
                Case "COMPANYNAME"
                    sortby = "company_id"
            End Select
            sSQL = sSQL & " order by Upper(" & sortby & ")" & SortOrder

            'sSQL = sSQL & " order by " & sortby & sortorder
        Else

            sSQL = sSQL & " order by u.User_ID " & SortOrder

        End If
        'Debug.Print sSQL
        'Rs.Open(sSQL, Conn, adOpenStatic, adLockReadOnly, adCmdText)
        Try
            GetDataset(DBConnectstring, sSQL, "adminuser", sErr, Rs)

            If IsNothing(nPageRecords) Then
                nPageRecords = 25
            Else

                'Rs.PageSize = nPageRecords
                nPagesize = nPageRecords  'one page contain records
            End If

            If Rs.Tables(0).Rows.Count > 0 Then
                nNumPages = (Rs.Tables(0).Rows.Count) / nPagesize
                If nPage < 1 Then nPage = 1
                If nPage > nNumPages Then nPage = nNumPages

                'Rs.Move (nPage - 1) * nPageRecords, 1
                'vUserlist = Rs.Tables(0).Rows.Count

                If nPage > Rs.Tables(0).Rows.Count Then
                    nNumPages = nPage
                    'nPage = Rs.PageCount
                Else
                    nNumPages = nPage
                End If

                'Rs.ActiveConnection = Nothing
            End If

            'FindUsers = vUserlist
            'Exit Function
        Catch ex As SqlException
            Dim i As Integer = 0

            For i = 0 To ex.Errors.Count - 1
                sErr = ex.Errors(i).Message.ToString()
            Next i
            ''/**use this code to debug**//

            LogErrorEvent(ErrMsg)

        End Try
        'Return vUserlist
        Return Nothing
    End Function

    Public Function FindAdminUsers(ByVal UID As String, _
            ByVal VID As String, _
            ByVal LastName As String, _
            ByVal FirstName As String, _
            ByVal Location As String, _
            ByVal sortby As String, _
            ByVal ToggleSortOrder As Boolean) As Object
        'On Error GoTo ErrorHandler
        Dim sSQL As String
        'Dim vUserlist As DataSet
        'Dim Conn As ADODB.Connection
        'Dim Rs As ADODB.Recordset
        Dim SortOrder As String = ""
        'Conn = New ADODB.Connection
        Dim Rs As DataSet = Nothing
        Dim sErr As String = ""
        Dim nPagesize As Integer

        'SaveSortField(sortby, SortOrder, ToggleSortOrder)

        sSQL = "SELECT "
        sSQL = sSQL & "   adminuser_id, "
        sSQL = sSQL & "   u.viaklix_ID, "
        sSQL = sSQL & "   first_name, "
        sSQL = sSQL & "   last_name, "
        sSQL = sSQL & "   location, "
        sSQL = sSQL & "   supervisor, "
        sSQL = sSQL & "   active "
        sSQL = sSQL & "FROM "
        sSQL = sSQL & "   adminuser"

        If UID <> "" Then
            sSQL = sSQL & " AND Upper(adminuser_id) like '%" & UCase(UID) & "%'"
        End If
        If VID <> "" Then
            sSQL = sSQL & " AND u.viaklix_Id like '%" & VID & "%'"
        End If

        If LastName <> "" Then
            sSQL = sSQL & " AND Upper(last_name) like '%" & UCase(LastName) & "%'"
        End If

        If FirstName <> "" Then
            sSQL = sSQL & " AND Upper(first_name) like '%" & UCase(FirstName) & "%'"
        End If
        If Location <> "" Then
            sSQL = sSQL & " AND Upper(location) like '%" & UCase(Location) & "%'"
        End If
        'If isELevelUser Then
        '    sSQL = sSQL & " AND adminuser_id IN "
        '    sSQL = sSQL & " ( "
        '    sSQL = sSQL & " select adminuser_id from (select * from adminuser where Upper(viaklix_Id) like "
        '    sSQL = sSQL & "'%" & UCase(VID) & "%') START WITH supervisor = (SELECT SUPERVISOR "
        '    sSQL = sSQL & "From users "
        '    sSQL = sSQL & "WHERE company_id = " & CID & " AND"
        '    sSQL = sSQL & "      viaklix_id ='" & SESSION_VIAKLIX_ID & "' And "
        '    sSQL = sSQL & "            user_id = '" & SESSION_USER_ID & "')"
        '    sSQL = sSQL & " CONNECT BY supervisor = prior user_id)"
        'End If

        If sortby <> "" Then

            Select Case sortby
                Case "UID"
                    sortby = "adminuser_id"
                Case "LASTNAME"
                    sortby = "last_name"
                Case "FIRSTNAME"
                    sortby = "first_name"
                Case "LOCATION"
                    sortby = "location"
                Case "SUPVISOR"
                    sortby = "supervisor"
                Case "ACTIVE"
                    sortby = "active"
                Case "VID"
                    sortby = "viaklix_ID"
            End Select
            sSQL = sSQL & " order by Upper(" & sortby & ")" & SortOrder

            'sSQL = sSQL & " order by " & sortby & sortorder
        Else

            sSQL = sSQL & " order by adminuser_id " & SortOrder

        End If
        'Debug.Print sSQL
        'Rs.Open(sSQL, Conn, adOpenStatic, adLockReadOnly, adCmdText)
        Try
            DBConnectstring = "Data Source=(Local); Initial Catalog=gaglobal10;Trusted_Connection=true;"
            GetDataset(DBConnectstring, sSQL, "adminuser", sErr, Rs)

            If IsNothing(nPageRecords) Then
                nPageRecords = 25
            Else

                'Rs.PageSize = nPageRecords
                nPagesize = nPageRecords  'one page contain records
            End If

            If Rs.Tables(0).Rows.Count > 0 Then
                nNumPages = (Rs.Tables(0).Rows.Count) / nPagesize
                If nPage < 1 Then nPage = 1
                If nPage > nNumPages Then nPage = nNumPages

                'Rs.Move (nPage - 1) * nPageRecords, 1
                'vUserlist = Rs.Tables(0).Rows.Count

                If nPage > Rs.Tables(0).Rows.Count Then
                    nNumPages = nPage
                    'nPage = Rs.PageCount
                Else
                    nNumPages = nPage
                End If

                'Rs.ActiveConnection = Nothing
            End If

            'FindUsers = vUserlist
            'Exit Function
        Catch ex As SqlException
            Dim i As Integer = 0

            For i = 0 To ex.Errors.Count - 1
                sErr = ex.Errors(i).Message.ToString()
            Next i
            ''/**use this code to debug**//

            LogErrorEvent(ErrMsg)

        End Try
        'Return vUserlist
        Return Nothing
    End Function

    Public Function EditUser(ByVal strUID As String, _
            ByVal CID As Integer, _
            ByVal VID As String, _
            ByVal action As String) As String

        Dim sSQL As String
        Dim bDeleteOk As Boolean
        Dim bUpdateOk As Boolean
        Dim Conn As SqlConnection
        'Dim Rs As ADODB.Recordset
        Dim sErr As String = ""
        Dim pwd As String
        Dim vAchar As Object
        Dim vAnum As Object
        Dim validpwd2 As Integer
        Dim validpwd1 As Integer
        Dim valid1 As Boolean
        Dim valid2 As Boolean
        Dim msg As String
        Dim i As Integer
        Dim a As Integer
        Dim ValidEmail As Integer

        If action = "Delete" Then

            sSQL = ""
            sSQL = "Update USERS SET Active ='N' WHERE User_ID =" & CheckString(strUID) & " AND Company_ID = " & CID & " AND Viaklix_ID =" & CheckString(VID)
            CallExecuteSQL(DBConnectstring, sSQL, sErr)
            If Len(sErr) = 0 Or IsNothing(sErr) Then
                bDeleteOk = True

                oAudit = CreateObject("viaAudit.AuditEvent")
                oAudit.DBConnectstring = DBConnectstring
                oAudit.SESSION_USER_ID = SESSION_USER_ID
                oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
                oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
                oAudit.AFFECTED_USER_ID = strUID
                oAudit.AFFECTED_VIAKLIX_ID = VID
                oAudit.AFFECTED_COMPANY_ID = CInt(CID)
                oAudit.AddInfo(68, ServerIP)
                oAudit.AddInfo(69, ServerTime)
                oAudit.AddInfo(70, SourceIP)
                oAudit.EventID = 9 '-----  User Disable
                x = oAudit.SaveEvent()
                oAudit = Nothing
                EditUser = bDeleteOk
                Exit Function
            End If
        ElseIf action = "Update" Then
            If EmailOld <> Email Then
                If Len(Email) > 0 Then
                    ValidEmail = InStrRev(Email, "@")
                    If CInt(ValidEmail) = 0 Then
                        msg = "Please enter a valid email address"
                        EditUser = msg
                        Exit Function
                    End If
                Else
                    msg = "Please enter a contact email address"
                    EditUser = msg
                    Exit Function
                End If
            End If

            If Password <> "" And OrigPassword <> Password Then

                vAchar = Split("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,!,@,#,$,%,^,&,*,(),_,-,=,+,<,>,?,/,:,;,',[,],{,},|,\,`,~", ",")
                vAnum = Split("1,2,3,4,5,6,7,8,9,0", ",")

                If Len(Password) < 6 Then
                    msg = "Please enter a minimum of six(6) characters. Your password must contain at least one letter and one number."
                    EditUser = msg
                    Exit Function
                Else
                    If Len(Password) > 15 Then
                        msg = "Please enter a maximum of fifteen (15) characters. Your password must contain at least one letter and one number."
                        EditUser = msg
                        Exit Function
                    End If

                    For i = 0 To UBound(vAchar)
                        validpwd1 = InStr(1, Password, vAchar(i), vbTextCompare)
                        If CLng(validpwd1) > 0 Then
                            valid1 = True
                            Exit For
                        End If
                    Next

                    If valid1 Then
                        For a = 0 To UBound(vAnum)
                            validpwd2 = InStr(Password, vAnum(a))
                            If CLng(validpwd2) > 0 Then
                                valid2 = True
                                Exit For
                            End If
                        Next
                        If Not valid2 Then
                            msg = "Your password must contain at least one number."
                            EditUser = msg
                            Exit Function
                        End If
                    Else
                        If Not valid1 Then
                            msg = "Your password must contain at least one letter."
                            EditUser = msg
                            Exit Function
                        End If
                    End If

                End If
            End If

            If Password <> "" And OrigPassword <> Password Then

                pwd = Password

            Else
                pwd = OrigPassword
            End If
            Conn = New SqlConnection
            Dim Cmd As SqlCommand
            Cmd = New SqlCommand
            'Conn.Open(DBConnectstring)
            With Cmd
                .Connection = Conn
                .CommandType = CommandType.StoredProcedure
                Cmd.CommandText = "VIAKLIX_PROCESSING.UPDUSER"
                .Parameters.Add(New SqlParameter("@i_userID", SqlDbType.VarChar, 15)).Value = strUID
                .Parameters.Add(New SqlParameter("@i_viaklixid", SqlDbType.VarChar, 15)).Value = VID
                .Parameters.Add(New SqlParameter("@i_companyid", SqlDbType.Int, 5)).Value = CInt(CID)
                .Parameters.Add(New SqlParameter("@i_password", SqlDbType.VarChar, 15)).Value = pwd
                .Parameters.Add(New SqlParameter("@i_roleid_old", SqlDbType.Int, 5)).Value = CInt(RoleIDOld)
                .Parameters.Add(New SqlParameter("@i_roleid_new", SqlDbType.Int, 5)).Value = CInt(RoleID)
                .Parameters.Add(New SqlParameter("@i_firstname_old", SqlDbType.VarChar, 20)).Value = FirstNameOld
                .Parameters.Add(New SqlParameter("@i_firstname_new", SqlDbType.VarChar, 20)).Value = FirstName
                .Parameters.Add(New SqlParameter("@i_lastname_old", SqlDbType.VarChar, 30)).Value = LastNameOld
                .Parameters.Add(New SqlParameter("@i_lastname_new", SqlDbType.VarChar, 30)).Value = LastName
                .Parameters.Add(New SqlParameter("@i_location_old", SqlDbType.VarChar, 50)).Value = LocationOld
                .Parameters.Add(New SqlParameter("@i_location_new", SqlDbType.VarChar, 50)).Value = Location
                .Parameters.Add(New SqlParameter("@i_phone_old", SqlDbType.VarChar, 20)).Value = PhoneOld
                .Parameters.Add(New SqlParameter("@i_phone_new", SqlDbType.VarChar, 20)).Value = Phone
                .Parameters.Add(New SqlParameter("@i_ext_old", SqlDbType.VarChar, 10)).Value = extOld
                .Parameters.Add(New SqlParameter("@i_ext_new", SqlDbType.VarChar, 10)).Value = ext
                .Parameters.Add(New SqlParameter("@i_emailaddress_old", SqlDbType.VarChar, 255)).Value = EmailOld
                .Parameters.Add(New SqlParameter("@i_emailaddress_new", SqlDbType.VarChar, 255)).Value = Email
                .Parameters.Add(New SqlParameter("@i_supervisor_old", SqlDbType.VarChar, 15)).Value = supervisorOld
                .Parameters.Add(New SqlParameter("@i_supervisor_new", SqlDbType.VarChar, 15)).Value = Supervisor
                .Parameters.Add(New SqlParameter("@i_active_old", SqlDbType.VarChar, 1)).Value = ActiveOld
                .Parameters.Add(New SqlParameter("@i_active_new", SqlDbType.VarChar, 1)).Value = Active
                .Parameters.Add(New SqlParameter("@0_errormsg", SqlDbType.VarChar, 255)).Direction = ParameterDirection.Output
            End With
            Try
                Cmd.Connection.Open()
                Cmd.ExecuteNonQuery()

                '------------------------------------------------------------------------
                'Returns a message to the calling ASP page.
                '------------------------------------------------------------------------
                If Not IsNothing(Cmd.Parameters("0_errormsg").Value) And (Cmd.Parameters("0_errormsg").Value <> " ") Then
                    'Debug.Print("Error Msg = " & Cmd.Parameters("0_errormsg" 
                    sErr = Cmd.Parameters("0_errormsg").Value
                    EditUser = sErr

                    Exit Function
                End If
                '------------------------------------------------------------------------

                'If Not IsNull(Cmd.Parameters("0_errormsg"  Then
                '    EditUser = False
                '    Debug.Print ("Error Msg = " & Cmd.Parameters("0_errormsg" 
                '    Exit Function
                'Else
                bUpdateOk = True
                EditUser = "OK"
                If ActiveOld <> Active Then
                    'oAudit = New gaAugit.AuditEvent
                    oAudit.DBConnectstring = DBConnectstring
                    oAudit.SESSION_USER_ID = SESSION_USER_ID
                    oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
                    oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
                    oAudit.AFFECTED_USER_ID = strUID
                    oAudit.AFFECTED_VIAKLIX_ID = VID
                    oAudit.AFFECTED_COMPANY_ID = CInt(CID)
                    oAudit.AddInfo(68, ServerIP)
                    oAudit.AddInfo(69, ServerTime)
                    oAudit.AddInfo(70, SourceIP)
                    If Active = "N" Then
                        oAudit.EventID = 9 '-----  User Disable
                        x = oAudit.SaveEvent()
                        oAudit = Nothing
                    Else
                        oAudit.EventID = 8  '-----  User Active
                        x = oAudit.SaveEvent()
                        oAudit = Nothing
                    End If
                End If

                If Password <> "" Then
                    'oAudit = CreateObject("viaAudit.AuditEvent")
                    'oAudit = New gaAugit.AuditEvent
                    oAudit.DBConnectstring = DBConnectstring
                    oAudit.SESSION_USER_ID = SESSION_USER_ID
                    oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
                    oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
                    oAudit.AFFECTED_USER_ID = strUID
                    oAudit.AFFECTED_VIAKLIX_ID = VID
                    oAudit.AFFECTED_COMPANY_ID = CInt(CID)
                    oAudit.AddInfo(68, ServerIP)
                    oAudit.AddInfo(69, ServerTime)
                    oAudit.AddInfo(70, SourceIP)
                    oAudit.EventID = 3 '-----  Change Password
                    x = oAudit.SaveEvent()
                    oAudit = Nothing

                End If

                Exit Function


            Catch ex As SqlException
                i = 0

                For i = 0 To ex.Errors.Count - 1
                    sErr = ex.Errors(i).Message.ToString()
                Next i
                ''/**use this code to debug**//

                LogErrorEvent(sErr)

            Finally
                If Not (Conn Is Nothing) Then
                    Conn.Close()
                End If
            End Try
        End If
        Return Nothing
    End Function

    'Public Function GetUserTerminals( _
    '        ByVal sUID As String, _
    '        ByVal sVID As String, _
    'ByVal nCID As Integer, _
    'Optional ByVal bOnlySelf As Boolean = False) As Object
    '    '-----  Function: UserManagement.GetUserTerminals
    '    '       Author: Brian S. Ward, for Nova Information Systems
    '    '       Date: 09.10.2001
    '    '       Purpose:    This function will return an array of
    '    '                   Terminal Numbers that the specified user
    '    '                   has authorization to. The array contains
    '    '                   direct User->Terminal associations, as well
    '    '                   as those held by subordinates.

    '    Dim Conn As SqlConnection
    '    Dim Rst As DataSet
    '    Dim Rst1 As DataSet
    '    Dim Rst2 As DataSet
    '    Dim sSQL As String
    '    Dim nUserCnt As Integer
    '    Dim aUsers As Object
    '    Dim i As Integer
    '    Dim bReturn As Boolean
    '    Dim aTerminals As Object
    '    'Dim nTermCnt As Integer
    '    Dim sErr As String = ""
    '    sSQL = ""
    '    'Rst = New DataSet
    '    Conn = New SqlConnection
    '    'Conn.Open(DBConnectstring)

    '    ' zdc: check to see if they want to only lookup
    '    ' terminals that belong to them, not subordinates
    '    If bOnlySelf Then
    '        sSQL = ""
    '        sSQL = sSQL & "SELECT count(USERS_TERMINALS.USER_ID) as numterms "
    '        sSQL = sSQL & "FROM "
    '        sSQL = sSQL & "USERS_TERMINALS, "
    '        sSQL = sSQL & "TERMINALS "
    '        sSQL = sSQL & "WHERE "
    '        sSQL = sSQL & "USERS_TERMINALS.COMPANY_ID = " & nCID & " and "
    '        sSQL = sSQL & "USERS_TERMINALS.VIAKLIX_ID = '" & sVID & "' and "
    '        sSQL = sSQL & "USERS_TERMINALS.USER_ID = '" & sUID & "' and "
    '        sSQL = sSQL & "USERS_TERMINALS.TERMINAL_NUMBER = TERMINALS.TERMINAL_NUMBER"

    '        'Set Rst = New ADODB.Recordset
    '        'Rst = Conn.Execute(sSQL)
    '        Rst = New DataSet
    '        GetDataset(DBConnectstring, sSQL, "users", sErr, Rst)
    '        nTermCnt = Rst.Tables(0).Rows(0).Item("numterms")

    '        sSQL = ""
    '        sSQL = sSQL & "SELECT "
    '        sSQL = sSQL & "USERS_TERMINALS.USER_ID, "
    '        sSQL = sSQL & "USERS_TERMINALS.PIN, "
    '        sSQL = sSQL & "USERS_TERMINALS.TERMINAL_NUMBER, "
    '        sSQL = sSQL & "TERMINALS.FRIENDLY_NAME, "
    '        sSQL = sSQL & "TERMINALS.MARKET "
    '        sSQL = sSQL & "FROM "
    '        sSQL = sSQL & "USERS_TERMINALS, "
    '        sSQL = sSQL & "TERMINALS "
    '        sSQL = sSQL & "WHERE "
    '        sSQL = sSQL & "USERS_TERMINALS.COMPANY_ID = 1 and "
    '        sSQL = sSQL & "USERS_TERMINALS.VIAKLIX_ID = '" & sVID & "' and "
    '        sSQL = sSQL & "USERS_TERMINALS.USER_ID = '" & sUID & "' and "
    '        sSQL = sSQL & "USERS_TERMINALS.TERMINAL_NUMBER = TERMINALS.TERMINAL_NUMBER"
    '        GetDataset(DBConnectstring, sSQL, "users", sErr, Rst1)
    '        'Rst = Conn.Execute(sSQL)
    '        If Rst1.Tables(0).Rows.Count > 0 Then
    '            ReDim aTerminals(nTermCnt, 5)
    '            nTermCnt = 0
    '            For nTermCnt = 0 To Rst1.Tables(0).Rows.Count > 0
    '                'Do While Not Rst.EOF
    '                aTerminals(nTermCnt, 0) = Rst1.Tables(0).Rows(nTermCnt).Item("USER_ID")
    '                aTerminals(nTermCnt, 1) = Rst1.Tables(0).Rows(nTermCnt).Item("PIN")
    '                aTerminals(nTermCnt, 2) = Rst1.Tables(0).Rows(nTermCnt).Item("TERMINAL_NUMBER")
    '                aTerminals(nTermCnt, 3) = Rst1.Tables(0).Rows(nTermCnt).Item("FRIENDLY_NAME")
    '                aTerminals(nTermCnt, 4) = Rst1.Tables(0).Rows(nTermCnt).Item("MARKET")
    '            Next
    '            'Rst.MoveNext()
    '            'nTermCnt = nTermCnt + 1
    '            'Loop
    '        End If
    '        'Rst = Nothing
    '        GetUserTerminals = aTerminals
    '    Else

    '        sSQL = sSQL & "select "
    '        sSQL = sSQL & "     USERS.USER_ID, "
    '        sSQL = sSQL & "     USERS.SUPERVISOR "
    '        sSQL = sSQL & "from "
    '        sSQL = sSQL & "     USERS "
    '        sSQL = sSQL & "where "
    '        sSQL = sSQL & "     USERS.VIAKLIX_ID = '" & sVID & "' and "
    '        sSQL = sSQL & "     USERS.USER_ID = '" & sUID & "' and "
    '        sSQL = sSQL & "     USERS.COMPANY_ID = " & nCID & " "
    '        'Rst.CursorLocation = adUseClient
    '        'Rst.Open(sSQL, Conn, adOpenStatic, adLockReadOnly, adCmdText)
    '        GetDataset(DBConnectstring, sSQL, "users", sErr, Rst)
    '        If Rst.Tables(0).Rows.Count > 0 Then
    '            nUserCnt = Rst.Tables(0).Rows.Count
    '            If nUserCnt > 0 Then
    '                ReDim aUsers(nUserCnt, 3)
    '                For i = 0 To nUserCnt - 1 Step 1
    '                    aUsers(i, 0) = Rst.Tables(0).Rows(i).Item("USER_ID")
    '                    aUsers(i, 1) = SafeString(Rst.Tables(0).Rows(i).Item("SUPERVISOR"))
    '                    If Rst.Tables(0).Rows(i).Item("USER_ID") = sUID Then
    '                        aUsers(i, 2) = 1
    '                    Else
    '                        aUsers(i, 2) = 0
    '                    End If

    '                Next i
    '                'Rst = Nothing
    '                bReturn = TagUserSubordinates(aUsers, sUID)
    '                nTermCnt = 0
    '                For i = 0 To UBound(aUsers) - 1 Step 1
    '                    If aUsers(i, 2) = 1 Then
    '                        sSQL = ""
    '                        sSQL = sSQL & "select "
    '                        sSQL = sSQL & "     count(USERS_TERMINALS.USER_ID) as TermCnt "
    '                        sSQL = sSQL & "from "
    '                        sSQL = sSQL & "     USERS_TERMINALS "
    '                        sSQL = sSQL & "where "
    '                        sSQL = sSQL & "     USERS_TERMINALS.COMPANY_ID = " & nCID & " and "
    '                        sSQL = sSQL & "     USERS_TERMINALS.VIAKLIX_ID = '" & sVID & "' and "
    '                        sSQL = sSQL & "     USERS_TERMINALS.USER_ID = '" & aUsers(i, 0) & "'"

    '                        Rst1 = New DataSet
    '                        GetDataset(DBConnectstring, sSQL, "users", sErr, Rst1)
    '                        If Rst1.Tables(0).Rows.Count > 0 Then
    '                            nTermCnt = nTermCnt + Rst1.Tables(0).Rows(0).Item("TermCnt")
    '                        End If
    '                        'Rst = Nothing
    '                    End If
    '                Next i
    '                ReDim aTerminals(nTermCnt, 5)
    '                nTermCnt = 0
    '                For i = 0 To UBound(aUsers) - 1 Step 1
    '                    If aUsers(i, 2) = 1 Then
    '                        sSQL = ""
    '                        sSQL = sSQL & "select "
    '                        sSQL = sSQL & "     USERS_TERMINALS.USER_ID, "
    '                        sSQL = sSQL & "     USERS_TERMINALS.PIN, "
    '                        sSQL = sSQL & "    USERS_TERMINALS.TERMINAL_NUMBER, "
    '                        sSQL = sSQL & "     TERMINALS.FRIENDLY_NAME, "
    '                        sSQL = sSQL & "     TERMINALS.MARKET "
    '                        sSQL = sSQL & "from "
    '                        sSQL = sSQL & "     USERS_TERMINALS, "
    '                        sSQL = sSQL & "     TERMINALS "
    '                        sSQL = sSQL & "where "
    '                        sSQL = sSQL & "     USERS_TERMINALS.COMPANY_ID = " & nCID & " and "
    '                        sSQL = sSQL & "     USERS_TERMINALS.VIAKLIX_ID = '" & sVID & "' and "
    '                        sSQL = sSQL & "     USERS_TERMINALS.USER_ID = '" & aUsers(i, 0) & "' and "
    '                        sSQL = sSQL & "     USERS_TERMINALS.TERMINAL_NUMBER = TERMINALS.TERMINAL_NUMBER"
    '                        Rst2 = New DataSet
    '                        GetDataset(DBConnectstring, sSQL, "users", sErr, Rst2)
    '                        If Rst2.Tables(0).Rows.Count > 0 Then
    '                            For nTermCnt = 0 To Rst2.Tables(0).Rows.Count - 1
    '                                'Do While Not Rst.EOF
    '                                aTerminals(nTermCnt, 0) = Rst2.Tables(0).Rows.Item("USER_ID")
    '                                aTerminals(nTermCnt, 1) = Rst2.Tables(0).Rows.Item("PIN")
    '                                aTerminals(nTermCnt, 2) = Rst2.Tables(0).Rows.Item("TERMINAL_NUMBER")
    '                                aTerminals(nTermCnt, 3) = Rst2.Tables(0).Rows.Item("FRIENDLY_NAME")
    '                                aTerminals(nTermCnt, 4) = Rst2.Tables(0).Rows.Item("MARKET")
    '                            Next
    '                            'Rst.MoveNext()
    '                            'nTermCnt = nTermCnt + 1
    '                            'Loop
    '                        End If
    '                        'Rst = Nothing
    '                    End If
    '                Next i
    '                GetUserTerminals = aTerminals
    '            Else
    '                Rst = Nothing
    '                GetUserTerminals = ""
    '            End If
    '        Else
    '            Rst = Nothing
    '            GetUserTerminals = ""
    '        End If

    '    End If

    '    '        Conn.Close()
    '    '        Conn = Nothing

    '    '        Exit Function
    '    'ErrorHandler:
    '    '        Call LogErrorEvent(".GetUserTerminals")

    '    '        If Not Rst Is Nothing Then
    '    '            If Rst.State <> adStateClosed Then
    '    '                Rst.Close()
    '    '            End If

    '    '            Rst = Nothing
    '    '        End If

    '    '        If Not Conn Is Nothing Then
    '    '            If Conn.State <> adStateClosed Then
    '    '                Conn.Close()
    '    '            End If

    '    '            Conn = Nothing
    '    '        End If

    'End Function

    Private Function TagUserSubordinates(ByRef aUsers As Object, _
            ByVal sUID As String) As Boolean
        '-----  Function: UserManagement.TagUserSubordinates
        '       Author: Brian S. Ward, for Nova Information Systems
        '       Date: 09.10.2001
        '       Purpose:    This function will recursively call itself
        '                   following parent-child relationships within
        '                   aUsers, tagging all indexes that are a child
        '                   or ancestor of the original passed-in sUID.
        '                   The tagging is handled by the 3rd dimension of
        '                   the aUsers array, 1 if tagged, 0 if not.
        On Error GoTo ErrorHandler
        Dim i As Integer
        Dim nReturn As Boolean
        Dim sPassUID As String
        For i = 0 To UBound(aUsers) - 1 Step 1
            If UCase(CStr(aUsers(i, 1))) = UCase(sUID) Then
                aUsers(i, 2) = 1
                sPassUID = aUsers(i, 0)
                nReturn = TagUserSubordinates(aUsers, sPassUID)
            End If
        Next i
        nReturn = True

ErrorHandler:
        Call LogErrorEvent(".TagUserSubordinates")

    End Function

    Private Function TagMerchantUsersHierarchy(ByRef aSortedUsers As Object, _
            ByRef vUserlist As Object, _
            ByRef nIndexLoc As Integer, _
    ByVal nLevel As Integer, _
            ByVal sParentSupervisor As String) As Boolean
        On Error GoTo ErrorHandler
        Dim i As Integer
        Dim bReturn As Boolean
        Dim sPassUID As String
        For i = 0 To UBound(vUserlist, 2)
            sPassUID = SafeString(vUserlist(1, i))
            If UCase(sPassUID) = UCase(sParentSupervisor) Then
                aSortedUsers(nIndexLoc, 0) = vUserlist(0, i)
                aSortedUsers(nIndexLoc, 1) = nLevel
                nIndexLoc = nIndexLoc + 1
                bReturn = TagMerchantUsersHierarchy(aSortedUsers, vUserlist, nIndexLoc, nLevel + 1, vUserlist(0, i))
            End If
        Next i

ErrorHandler:
        Call LogErrorEvent(".TagMerchantUsersHierarchy")

    End Function

    Public Function ChangePassword(ByVal sUID As String, _
            ByVal nCID As Integer, _
            ByVal sVID As String, _
            ByVal OrigPwd As String, _
            ByVal sNewPwd As String) As String


        Dim Conn As New SqlConnection
        Dim Rs As New DataSet
        Dim sSQL As String
        Dim sHashpassword As String
        Dim vAchar As Object
        Dim vAnum As Object
        Dim validpwd2 As Integer
        Dim validpwd1 As Integer
        Dim valid1 As Boolean
        Dim valid2 As Boolean
        Dim msg As String = ""
        Dim i As Integer
        Dim a As Integer
        'Conn.Open(DBConnectstring)
        'Rs.ActiveConnection = Conn
        'Rs.CursorLocation = adUseClient
        '======
        If sNewPwd <> "" Then
            vAchar = Split("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,!,@,#,$,%,^,&,*,(),_,-,=,+,<,>,?,/,:,;,',[,],{,},|,\,`,~", ",")
            vAnum = Split("1,2,3,4,5,6,7,8,9,0", ",")

            If Len(sNewPwd) < 6 Then
                msg = "Please enter a minimum of six(6) characters. Your password must contain at least one letter and one number."
                ChangePassword = msg
                Exit Function
            Else

                For i = 0 To UBound(vAchar)
                    validpwd1 = InStr(1, sNewPwd, vAchar(i), vbTextCompare)
                    If CLng(validpwd1) > 0 Then
                        valid1 = True
                        Exit For
                    End If
                Next

                If valid1 Then
                    For a = 0 To UBound(vAnum)
                        validpwd2 = InStr(sNewPwd, vAnum(a))
                        If CLng(validpwd2) > 0 Then
                            valid2 = True
                            Exit For
                        End If
                    Next
                    If Not valid2 Then
                        msg = "Your password must contain at least one number."
                        ChangePassword = msg
                        Exit Function
                    End If
                Else
                    If Not valid1 Then
                        msg = "Your password must contain at least one letter."
                        ChangePassword = msg
                        Exit Function
                    End If
                End If

            End If
        End If

        '========
        sSQL = "SELECT * FROM USERS"
        sSQL = sSQL & " WHERE User_ID=" & CheckString(sUID)
        sSQL = sSQL & " AND Password = VIAKLIX_LOGIN.Hash_Password(" & CheckString(sUID) & ", " & CheckString(OrigPwd) & ")"
        ''Rs.Open(sSQL, Conn, adOpenForwardOnly, adLockReadOnly, adCmdText)
        Try
            GetDataset(DBConnectstring, sSQL, "users", msg, Rs)
            If Rs.Tables(0).Rows.Count > 0 Then
                sHashpassword = SafeString(Rs.Tables(0).Rows(0).Item("Password"))
                Dim Cmd As SqlCommand
                Cmd = New SqlCommand
                With Cmd
                    .Connection = Conn
                    .CommandType = CommandType.StoredProcedure
                    .CommandText = "VIAKLIX_MERCHANTMAINT.CHANGEPASSWORD"
                    .Parameters.Add(New SqlParameter("@i_vid", SqlDbType.VarChar, 15)).Value = sVID
                    .Parameters.Add(New SqlParameter("@i_uid", SqlDbType.VarChar, 15)).Value = sUID
                    .Parameters.Add(New SqlParameter("@i_cid", SqlDbType.Int, 5)).Value = CInt(nCID)
                    .Parameters.Add(New SqlParameter("@i_password_old", SqlDbType.VarChar, 15)).Value = sHashpassword
                    .Parameters.Add(New SqlParameter("@i_password_new", SqlDbType.VarChar, 15)).Value = sNewPwd
                    .Parameters.Add(New SqlParameter("@0_errormsg", SqlDbType.VarChar, 255)).Direction = ParameterDirection.Output
                End With
                Cmd.Connection.Open()
                Cmd.ExecuteNonQuery()
                If Not IsNothing(Cmd.Parameters("0_errormsg").Value) Then
                    'Debug.Print("Error Msg = " & Cmd.Parameters("0_errormsg" 
                    msg = Cmd.Parameters("0_errormsg").Value
                    ChangePassword = msg
                    Conn.Close()
                    Exit Function
                Else
                    ChangePassword = "OK"
                    'oAudit = New gaAugit.AuditEvent   ''CreateObject("viaAudit.AuditEvent")
                    oAudit.DBConnectstring = DBConnectstring
                    oAudit.SESSION_USER_ID = SESSION_USER_ID
                    oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
                    oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
                    oAudit.AFFECTED_USER_ID = sUID
                    oAudit.AFFECTED_VIAKLIX_ID = sVID
                    oAudit.AFFECTED_COMPANY_ID = CInt(nCID)
                    oAudit.AddInfo(68, ServerIP)
                    oAudit.AddInfo(69, ServerTime)
                    oAudit.AddInfo(70, SourceIP)
                    oAudit.EventID = 3  '-----  Password Change
                    x = oAudit.SaveEvent()
                    oAudit = Nothing

                    Exit Function
                End If
            Else
                msg = "You do not have the permission to change the password or your old password is not correct."
                ChangePassword = msg
                Conn.Close()
                Conn = Nothing
                Exit Function
            End If

        Catch ex As SqlException
            i = 0
            For i = 0 To ex.Errors.Count - 1
                msg = ex.Errors(i).Message.ToString()
            Next i
            ''/**use this code to debug**//

            LogErrorEvent(msg)
            ChangePassword = msg
        Finally
            If Not (Conn Is Nothing) Then
                Conn.Close()
            End If
        End Try


    End Function

    Public Function AddTerminalAssoc(ByVal sUID As String, _
            ByVal sVID As String, _
    ByVal nCID As Integer, _
            ByVal sTerminalNumber As String) As Boolean

        'Dim sPin As String
        'Dim i As Integer
        'Dim valpha As Object
        ' Dim nSides As Integer
        'Dim GeneralResult As Integer

        'CW 5/14/02 Using generic function to generate PIN
        pinlength = 6
        'sPin = GeneratePin()

        Dim Conn As SqlConnection
        Conn = New SqlConnection
        Dim Cmd As SqlCommand
        Cmd = New SqlCommand
        With Cmd
            .Connection = Conn
            .CommandType = CommandType.StoredProcedure
            Cmd.CommandText = "VIAKLIX_PROCESSING.InsUserTerminal"
            .Parameters.Add(New SqlParameter("@i_cid", SqlDbType.Int, 4)).Value = nCID
            .Parameters.Add(New SqlParameter("@i_vid", SqlDbType.VarChar, 15)).Value = sVID
            .Parameters.Add(New SqlParameter("@i_uid", SqlDbType.VarChar, 15)).Value = sUID
            '.Parameters.Add(New SqlParameter("@i_pin", SqlDbType.VarChar, 6)).Value = sPin
            .Parameters.Add(New SqlParameter("@i_tnumber", SqlDbType.VarChar, 22)).Value = sTerminalNumber
            .Parameters.Add(New SqlParameter("@0_errormsg", SqlDbType.VarChar, 255)).Direction = ParameterDirection.Output
        End With
        Cmd.Connection.Open()
        Cmd.ExecuteNonQuery()

        '------------------------------------------------------------------------
        'Returns a message to the calling ASP page.
        '------------------------------------------------------------------------
        If Not IsNothing(Cmd.Parameters("0_errormsg").Value) Then
            AddTerminalAssoc = False

            'Debug.Print("Error Msg = " & Cmd.Parameters("0_errormsg" 
            ErrMsg = Cmd.Parameters("0_errormsg").Value

            Cmd = Nothing
            Conn.Close()
            Conn = Nothing
            Exit Function
        End If
        '------------------------------------------------------------------------

        Cmd = Nothing
        Conn.Close()
        Conn = Nothing
        AddTerminalAssoc = True
        'oAudit = New gaAugit.AuditEvent ''CreateObject("viaAudit.AuditEvent")
        oAudit.DBConnectstring = DBConnectstring
        oAudit.SESSION_USER_ID = SESSION_USER_ID
        oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
        oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
        oAudit.AFFECTED_USER_ID = sUID
        oAudit.AFFECTED_VIAKLIX_ID = sVID
        oAudit.AFFECTED_COMPANY_ID = CInt(nCID)
        oAudit.EventID = 16  '----- Add new terminal number
        x = oAudit.SaveEvent()
        oAudit = Nothing
        Exit Function


    End Function

    Public Function UpdateTerminalAssoc(ByVal sUID As String, _
            ByVal sVID As String, _
    ByVal nCID As Integer, _
            ByVal sTerminalNumber As String, _
            ByVal sPin As String) As String

        Dim UpdatePin As Boolean
        Dim Conn As SqlConnection
        Dim sSQL As String
        'm sNewPin As String
        Dim vPinList As Object
        Dim Rst As DataSet
        Dim sqlstr As String
        Dim i As Integer
        ' Dim c As Integer
        Dim colctr As Integer
        Dim recdctr As Integer
        Dim Rs2 As DataSet
        Dim sErr As String = ""
        'sNewPin = GeneratePin()

        sqlstr = ""
        sqlstr = sqlstr & "Select "
        sqlstr = sqlstr & "   Pin "
        sqlstr = sqlstr & "FROM "
        sqlstr = sqlstr & "   USERS_TERMINALS "
        sqlstr = sqlstr & "WHERE "
        sqlstr = sqlstr & "   Viaklix_ID = '" & sVID & "' "
        Conn = New SqlConnection
        Rst = New DataSet
        Try
            'Rst.Open(sqlstr, Conn, adOpenStatic, adLockReadOnly, adCmdText)
            GetDataset(DBConnectstring, sqlstr, "users", sErr, Rst)
            If Rst.Tables(0).Rows.Count > 0 Then
                vPinList = Rst.Tables(0).Rows.Count
                For colctr = 0 To UBound(vPinList, 2)
                    For recdctr = 0 To UBound(vPinList, 1)
                        'If sNewPin = vPinList(recdctr, colctr) Then
                        '    sNewPin = ""
                        '    'sNewPin = GeneratePin()
                        'End If
                    Next
                Next

            End If

            'If Len(sNewPin) > 0 Then
            Rs2 = New DataSet
            sSQL = ""
            sSQL = sSQL & "update USERS_TERMINALS set "
            'sSQL = sSQL & "Pin = '" & sNewPin & "' "
            sSQL = sSQL & "where USER_ID = '" & sUID & "' and "
            sSQL = sSQL & "VIAKLIX_ID = '" & sVID & "' and "
            sSQL = sSQL & "COMPANY_ID = " & nCID & " and "
            sSQL = sSQL & "TERMINAL_NUMBER = '" & sTerminalNumber & "'"
            GetDataset(DBConnectstring, sSQL, "users", sErr, Rs2)
            'Conn.Execute(sSQL)

            If Len(sErr) = 0 Or IsNothing(sErr) Then
                UpdatePin = True
            End If

            'End If

            If UpdatePin = True Then
                '---save audit event
                oAudit = CreateObject("viaAudit.AuditEvent")
                oAudit.DBConnectstring = DBConnectstring
                oAudit.SESSION_USER_ID = SESSION_USER_ID
                oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
                oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
                oAudit.AFFECTED_USER_ID = sUID
                oAudit.AFFECTED_VIAKLIX_ID = sVID
                oAudit.AFFECTED_COMPANY_ID = CInt(nCID)
                oAudit.AddInfo(68, ServerIP)
                oAudit.AddInfo(69, ServerTime)
                oAudit.AddInfo(70, SourceIP)
                oAudit.EventID = 4  '-----  Pin change
                x = oAudit.SaveEvent()
                oAudit = Nothing
            End If
            'UpdateTerminalAssoc = sNewPin

        Catch ex As SqlException
            i = 0
            For i = 0 To ex.Errors.Count - 1
                ErrMsg = ex.Errors(i).Message.ToString()
            Next i
            ''/**use this code to debug**//

            LogErrorEvent(ErrMsg)

        End Try
        Return Nothing
    End Function

    Public Function DeleteTerminalAssoc(ByVal sUID As String, _
            ByVal sVID As String, _
    ByVal nCID As Integer, _
            ByVal sTerminalNumber As String) As Boolean

        DeleteTerminalAssoc = False
        Dim ds As DataSet
        Dim sErr As String = ""
        Dim sSQL As String
        sSQL = ""
        sSQL = sSQL & "delete from USERS_TERMINALS "
        sSQL = sSQL & "where USER_ID = '" & sUID & "' and "
        sSQL = sSQL & "VIAKLIX_ID = '" & sVID & "' and "
        sSQL = sSQL & "COMPANY_ID = " & nCID & " and "
        sSQL = sSQL & "TERMINAL_NUMBER = '" & sTerminalNumber & "'"
        Try
            ds = New DataSet
            GetDataset(DBConnectstring, sSQL, "users", sErr, ds)
            If Len(sErr) > 0 Then
                DeleteTerminalAssoc = True
            Else
                DeleteTerminalAssoc = False
            End If
            ' dit = New gaAugit.AuditEvent 'CreateObject("viaAudit.AuditEvent")
            oAudit.DBConnectstring = DBConnectstring
            oAudit.SESSION_USER_ID = SESSION_USER_ID
            oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
            oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
            oAudit.AFFECTED_USER_ID = sUID
            oAudit.AFFECTED_VIAKLIX_ID = sVID
            oAudit.AFFECTED_COMPANY_ID = CInt(nCID)
            oAudit.EventID = 17  '-----  Pin and terminal number deletion
            x = oAudit.SaveEvent()
            oAudit = Nothing
            Exit Function
        Catch ex As SqlException

            Dim i As Integer = 0

            For i = 0 To ex.Errors.Count - 1
                ErrMsg = ex.Errors(i).Message.ToString()
            Next i
            ''/**use this code to debug**//

            LogErrorEvent(ErrMsg)
            DeleteTerminalAssoc = False
        End Try
    End Function

    Private Sub LogErrorEvent(ByVal sOrigin As String)
        Dim sErrMsg As String
        sErrMsg = ""
        sErrMsg = sErrMsg & "viaUserManagment.UserManager" & sOrigin & vbCrLf
        sErrMsg = sErrMsg & "Source: " & Err.Source & vbCrLf
        sErrMsg = sErrMsg & "Number: " & Err.Number & vbCrLf
        sErrMsg = sErrMsg & "Description: " & Err.Description
        'App.LogEvent(sErrMsg, vbLogEventTypeError)
        'Debug.Print(sErrMsg)
    End Sub

    Public Function AddUserTerminals(ByVal UID As String, _
            ByVal VID As String, _
            ByVal CID As Integer, _
            ByVal TID As String) As Boolean



        Dim Conn As SqlConnection
        Dim Rs As DataSet
        Dim Cmd As SqlCommand
        Dim sSQL As String
        ' Dim sPin As String
        ' Dim GeneralResult As Integer
        'Dim i As Integer
        Dim sErr As String = ""
        Conn = New SqlConnection
        'Conn.Open(DBConnectstring)

        'CW 5/14/02 using the existing function to generate the PIN.
        pinlength = 6
        'sPin = GeneratePin()

        sSQL = ""
        sSQL = "SELECT  Terminal_Number "
        sSQL = sSQL & "FROM TERMINALS "
        sSQL = sSQL & "WHERE "
        sSQL = sSQL & "   Viaklix_id = '" & VID & "' and "
        sSQL = sSQL & "   terminal_Number = '" & TID & "'"
        Rs = New DataSet
        GetDataset(DBConnectstring, sSQL, "users", sErr, Rs)
        If Not Rs.Tables(0).Rows.Count > 0 Then

            Cmd = New SqlCommand
            With Cmd
                .Connection = Conn
                .CommandType = CommandType.StoredProcedure
                Cmd.CommandText = "VIAKLIX_PROCESSING.INSUSERTERMINAL"
                .Parameters.Add(New SqlParameter("@i_cid", SqlDbType.Int, 4)).Value = CInt(CID)
                .Parameters.Add(New SqlParameter("@i_vid", SqlDbType.VarChar, 15)).Value = VID
                .Parameters.Add(New SqlParameter("@i_uid", SqlDbType.VarChar, 15)).Value = UID
                '.Parameters.Add(New SqlParameter("@i_pin", SqlDbType.VarChar, 6)).Value = sPin
                .Parameters.Add(New SqlParameter("@i_tnumber", SqlDbType.VarChar, 22)).Value = TID
                .Parameters.Add(New SqlParameter("@0_errormsg", SqlDbType.VarChar, 255)).Direction = ParameterDirection.Output
            End With
            Cmd.Connection.Open()
            Cmd.ExecuteNonQuery()

            '------------------------------------------------------------------------
            'Returns a message to the calling ASP page.
            '------------------------------------------------------------------------
            If Not IsNothing(Cmd.Parameters("0_errormsg").Value) Then
                AddUserTerminals = False

                'Debug.Print("Error Msg = " & Cmd.Parameters("0_errormsg" 
                ErrMsg = Cmd.Parameters("0_errormsg").Value

                Exit Function
            End If
            '------------------------------------------------------------------------

            AddUserTerminals = True
            oAudit = CreateObject("viaAudit.AuditEvent")
            oAudit.DBConnectstring = DBConnectstring
            oAudit.SESSION_USER_ID = SESSION_USER_ID
            oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
            oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
            oAudit.AFFECTED_USER_ID = UID
            oAudit.AFFECTED_VIAKLIX_ID = VID
            oAudit.AFFECTED_COMPANY_ID = CInt(CID)
            oAudit.EventID = 16  '-----  Add new terminal number
            x = oAudit.SaveEvent()
            oAudit = Nothing
            Cmd = Nothing
            Conn.Close()
            Conn = Nothing
            Exit Function

        End If

        'Exit Function
        'ErrorHandler:
        '        Call LogErrorEvent(".AddUserTerminals")
        '        Exit Function
        Return Nothing
    End Function
    'Private Function GeneratePin() As String
    '    'On Error GoTo ErrorHandler
    '    Dim i As Integer
    '    Dim sNewPin As String
    '    Dim valpha As Object
    '    Dim nSides As Integer
    '    Dim GeneralResult As Integer

    '    'CW 5/14/02 Added J to the list of letters and modified the algorithm to allow for
    '    'selection of the first 10 letters A-J, instead of 0-9,K-Z only.

    '    If Len(pinlength) > 0 Then
    '        valpha = Split("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z", ",")
    '        If pintype = "Numpin" Then
    '            nSides = 10
    '        Else
    '            nSides = 36
    '        End If

    '        For i = 0 To pinlength - 1
    '            Randomize()
    '            GeneralResult = Int(nSides * Rnd())
    '            If pintype = "Numpin" Then
    '                If GeneralResult < 10 Then
    '                    sNewPin = sNewPin & GeneralResult
    '                End If
    '            Else
    '                If GeneralResult < 10 Then
    '                    sNewPin = sNewPin & GeneralResult
    '                Else
    '                    sNewPin = sNewPin & valpha(GeneralResult - 10)
    '                End If
    '            End If
    '        Next
    '        GeneratePin = sNewPin
    '    End If
    '    Exit Function
    '    'ErrorHandler:
    '    '        Call LogErrorEvent(".GeneralResult")
    '    '        Exit Function
    'End Function
    Public Function LockedStatus(ByVal UID As String, _
            ByVal VID As String, _
            ByVal CID As Integer) As Boolean
        Dim bLocked As Boolean
        Dim nCount As Integer
        Dim Rst As DataSet
        Dim sErr As String = ""
        Dim sSQL As String
        If VID <> "000000" Then
            nCount = 0

            Rst = New DataSet

            sSQL = "SELECT Event_ID "
            sSQL = sSQL & "FROM (select Event_ID, DateTime "
            sSQL = sSQL & "FROM Audits "
            sSQL = sSQL & "WHERE ((Event_ID = 1 or Event_ID = 2) and "
            sSQL = sSQL & "AFFECTING_USER_ID = '" & Replace(UID, "'", "''") & "' and "
            sSQL = sSQL & "AFFECTING_VIAKLIX_ID = '" & Replace(VID, "'", "''") & "' and "
            sSQL = sSQL & "AFFECTING_COMPANY_ID = " & CID & " )"
            sSQL = sSQL & "OR ( Event_ID = 20 AND "
            sSQL = sSQL & "AFFECTING_USER_ID = '" & Replace(UID, "'", "''") & "' and "
            sSQL = sSQL & "AFFECTING_VIAKLIX_ID = '" & Replace(VID, "'", "''") & "' and "
            sSQL = sSQL & "AFFECTING_COMPANY_ID = " & CID & " )"
            sSQL = sSQL & "ORDER BY DateTime desc) "
            sSQL = sSQL & "WHERE ROWNUM <= 3"

            'Rst.Open(sSQL, DBConnectstring, adOpenForwardOnly, adLockReadOnly)
            GetDataset(DBConnectstring, sSQL, "users", sErr, Rst)
            If Len(sErr) = 0 Then
                bLocked = True
                For nCount = 0 To Rst.Tables(0).Rows.Count - 1
                    'Do While Not Rst.EOF
                    'nCount = nCount + 1
                    If CLng(Rst.Tables(0).Rows(nCount).Item("Event_ID")) <> 2 Then
                        bLocked = False
                    End If
                Next

                If nCount >= 3 And bLocked = True Then
                    LockedStatus = True
                Else
                    LockedStatus = False
                End If
            Else
                LogErrorEvent(sErr)
                LockedStatus = False
            End If
        Else
            LockedStatus = False
        End If
    End Function

    Public Sub UnLockAccount(ByVal UID As String, _
            ByVal VID As String, _
            ByVal CID As Integer)
        'oAudit = New gaAugit.AuditEvent  'CreateObject("viaaudit.AuditEvent")
        oAudit.DBConnectstring = DBConnectstring
        '-----  saving merchant unlock event
        oAudit.EventID = 20 '-----  Merchant Unlock
        oAudit.DBConnectstring = DBConnectstring
        oAudit.SESSION_USER_ID = SESSION_USER_ID
        oAudit.SESSION_VIAKLIX_ID = SESSION_VIAKLIX_ID
        oAudit.SESSION_COMPANY_ID = SESSION_COMPANY_ID
        oAudit.AFFECTED_USER_ID = UID
        oAudit.AFFECTED_VIAKLIX_ID = VID
        oAudit.AFFECTED_COMPANY_ID = CInt(CID)
        '-----  BW 12/18/01 server ip, server time, and source ip auditing
        oAudit.AddInfo(68, ServerIP)
        oAudit.AddInfo(69, ServerTime)
        oAudit.AddInfo(70, SourceIP)
        '-----  end server ip, server time, and source ip auditing
        Call oAudit.SaveEvent()
        oAudit = Nothing
    End Sub

    Public Function GetUserUniqTerminals(ByVal sUID As String, _
            ByVal sVID As String, _
            ByVal nCID As Integer, _
            ByVal sCurrentUser As String) As Object

        Dim Conn As SqlConnection
        Dim Rst As DataSet
        Dim Rst1 As DataSet
        Dim sSQL As String
        Dim Supervisor As String
        Dim nCt As Integer
        Dim aGetTerminals As Object
        Dim bUseSupervisor As Boolean
        Dim sErr As String = ""
        sSQL = ""
        Conn = New SqlConnection
        'Conn.Open(DBConnectstring)

        Rst = New DataSet
        'Rst.ActiveConnection = Conn
        'Rst.CursorLocation = adUseClient

        If sUID = sVID Then
            sSQL = sSQL & "SELECT "
            sSQL = sSQL & "TERMINAL_NUMBER, "
            sSQL = sSQL & "FRIENDLY_NAME "
            'sSQL = sSQL & "MARKET "
            sSQL = sSQL & "from "
            sSQL = sSQL & "    Terminals "
            sSQL = sSQL & "Where "
            sSQL = sSQL & "   VIAKLIX_ID ='" & sVID & "'"
            GetDataset(DBConnectstring, sSQL, "users", sErr, Rst)
        Else
            bUseSupervisor = False

            sSQL = sSQL & "select "
            sSQL = sSQL & "     USERS.SUPERVISOR "
            sSQL = sSQL & "from "
            sSQL = sSQL & "     USERS "
            sSQL = sSQL & "where "
            sSQL = sSQL & "     USERS.VIAKLIX_ID = '" & sVID & "' and "
            sSQL = sSQL & "     USERS.USER_ID = '" & sUID & "' and "
            sSQL = sSQL & "     USERS.COMPANY_ID = " & nCID & " "
            GetDataset(DBConnectstring, sSQL, "users", sErr, Rst)
            If Rst.Tables(0).Rows.Count > 0 Then
                Supervisor = SafeString(Rst.Tables(0).Rows(0).Item("SUPERVISOR"))
            End If


            'If sCurrentUser = Supervisor Then
            '    bUseSupervisor = True
            'End If

            sSQL = ""
            sSQL = sSQL & "select "
            sSQL = sSQL & "     Distinct(UT.terminal_number), "
            sSQL = sSQL & "     T.FRIENDLY_NAME "
            sSQL = sSQL & "from "
            sSQL = sSQL & "     USERS_TERMINALS UT, "
            sSQL = sSQL & "     TERMINALS T "
            sSQL = sSQL & "where "
            sSQL = sSQL & "     UT.VIAKLIX_ID = '" & sVID & "' and "
            'If bUseSupervisor Then
            '    sSQL = sSQL & "     UT.USER_ID = '" & Supervisor & "' and "
            'Else
            '    sSQL = sSQL & "     UT.USER_ID = '" & sCurrentUser & "' and "
            'End If
            sSQL = sSQL & "     UT.COMPANY_ID = " & nCID & " and "
            sSQL = sSQL & "     T.VIAKLIX_ID = UT.VIAKLIX_ID and "
            sSQL = sSQL & "     UT.TERMINAL_NUMBER = T.TERMINAL_NUMBER and "
            sSQL = sSQL & "     UT.TERMINAL_NUMBER NOT IN( "
            sSQL = sSQL & "Select "
            sSQL = sSQL & "     TERMINAL_NUMBER "
            sSQL = sSQL & "From "
            sSQL = sSQL & "    USERS_TERMINALS "
            sSQL = sSQL & "Where "
            sSQL = sSQL & "    USER_ID = '" & sUID & "' and "
            sSQL = sSQL & "    VIAKLIX_ID ='" & sVID & "')"
        End If
        'Debug.Print sSQL
        Rst1 = New DataSet
        GetDataset(DBConnectstring, sSQL, "users", sErr, Rst1)
        If Rst1.Tables(0).Rows.Count > 0 Then
            nCt = Rst1.Tables(0).Rows.Count
            'Do While Not Rst.EOF
            '    nCt = nCt + 1
            '    Rst.MoveNext()
            'Loop
            ReDim aGetTerminals(nCt, 2)
            'Rst.Requery()
            nCt = 0
            'Do While Not Rst.EOF
            For nCt = 0 To Rst1.Tables(0).Rows.Count - 1
                aGetTerminals(nCt, 0) = Rst1.Tables(0).Rows(nCt).Item("TERMINAL_NUMBER")
                aGetTerminals(nCt, 1) = Rst1.Tables(0).Rows(nCt).Item("FRIENDLY_NAME")
            Next
            'n(Ct = nCt + 1)
            'Rst.MoveNext()
            'Loop
            GetUserUniqTerminals = aGetTerminals
            'Rst.Close()
            'Rst = Nothing
            'Conn.Close()
            'Conn = Nothing
        Else
            GetUserUniqTerminals = ""
            'Rst.Close()
            'Rst = Nothing
            'Conn.Close()
            'Conn = Nothing
        End If

        Exit Function
        'ErrorHandler:
        '        Call LogErrorEvent(".GetUserUniqTerminals")

        '        If Not Rst Is Nothing Then
        '            If Rst.State <> adStateClosed Then
        '                Rst.Close()
        '            End If

        '            Rst = Nothing
        '        End If

        '        If Not Conn Is Nothing Then
        '            If Conn.State <> adStateClosed Then
        '                Conn.Close()
        '            End If

        '            Conn = Nothing
        '        End If

    End Function


    ' use the VT session vars in the db to store the
    'Private Sub SaveSortField(ByVal SortField As String, ByRef SortOrder As String, Optional ByVal ToggleSortOrder As Boolean = True)



    '    Dim objConn As SqlConnection
    '    Dim objCmd As SqlCommand
    '    Dim objRs As DataSet
    '    Dim strSQL As String
    '    Dim StoredField As String
    '    Dim StoredOrder As String
    '    'Dim SortOrder As String
    '    Dim StoredPage As String
    '    Dim UpdateField As Boolean
    '    Dim SearchStatus As String
    '    Dim sqlAdpt As SqlDataAdapter

    '    'objConn = CreateObject("adodb.Connection")
    '    'objCmd = CreateObject("ADODB.Command")
    '    'objRs = CreateObject("adodb.Recordset")

    '    'SearchStatus = GetSearchStatus
    '    'objConn.Open(DBConnectstring)
    '    objRs = New DataSet
    '    UpdateField = True


    '    With objCmd
    '        .Connection = objConn
    '        .CommandText = "VIAKLIX_VIRTUAL_TERMINAL.GetVTSortCriteria"
    '        .CommandType = CommandType.StoredProcedure
    '        .Parameters.Add(New SqlParameter("@sessionid", SqlDbType.VarChar, 40)).Value = SessionID
    '        .Parameters.Add(New SqlParameter("@errormsg", SqlDbType.VarChar, 50)).Direction = ParameterDirection.Output
    '    End With
    '    sqlAdpt.SelectCommand.CommandType = CommandType.StoredProcedure
    '    sqlAdpt.Fill(objRs, "GetVTSortCriteria")


    '    'objRs = objCmd.Execute
    '    'objCmd.Connection.Open()
    '    'objCmd.ExecuteNonQuery()

    '    '------------------------------------------------------------------------
    '    'Returns a message to the calling ASP page.
    '    '------------------------------------------------------------------------
    '    If Not IsNothing(objCmd.Parameters("errormsg").Value) Then

    '        'Debug.Print("Error Msg = " & objCmd.Parameters("errormsg" 
    '        ErrMsg = objCmd.Parameters("errormsg").Value

    '        'objCmd = Nothing
    '        'objConn.Close()
    '        'objConn = Nothing
    '        Exit Sub
    '    End If
    '    '------------------------------------------------------------------------

    '    If objRs.Tables(0).Rows.Count > 0 Then
    '        StoredField = SafeString(objRs.Tables(0).Rows(0).Item(0))
    '        StoredOrder = SafeString(objRs.Tables(0).Rows(0).Item(1))

    '        If IsNothing(objRs.Tables(0).Rows(0).Item(2)) Then
    '            StoredPage = 0
    '        Else
    '            StoredPage = SafeString(objRs.Tables(0).Rows(0).Item(2))
    '        End If


    '        objConn.Close()
    '    End If
    '    If ToggleSortOrder Then
    '        If UCase(StoredField) = UCase(SortField) Then
    '            UpdateField = False
    '            If CInt(StoredPage) = CInt(nPage) Then
    '                Select Case UCase(StoredOrder)
    '                    Case "DESC"
    '                        SortOrder = "ASC"
    '                    Case Else
    '                        SortOrder = "DESC"
    '                End Select
    '            Else
    '                SortOrder = StoredOrder
    '                SetCurrentPage()
    '            End If
    '        Else
    '            SortOrder = "ASC"
    '        End If

    '        SaveSortOrder(SortOrder)
    '    Else
    '        SortOrder = StoredOrder
    '        SetCurrentPage()
    '    End If


    '    '    If UpdateField Then
    '    '        If (SearchStatus) = "N" Then
    '    '            Select Case SortField
    '    '                Case "settleresponse", "settlementdatetime", "netamount", "salecount", "voidcount", "creditcount", "batch_id"
    '    '                Case Else
    '    '                    SortField = "settlementdatetime"
    '    '            End Select
    '    '        Else
    '    '            Select Case SortField
    '    '                Case "batch_id", "txn_type", "txn_date_time", "tranamount", "auth_avs_response", "cvv2response", "card_number", "txn_id"
    '    '                Case Else
    '    '                    SortField = "txn_date_time"
    '    '            End Select
    '    '        End If
    '    '    Else
    '    '        Select Case SortField
    '    '            Case "txn_id", "txn_type", "txn_date_time", "tranamount", "card_number"
    '    '            Case Else
    '    '                SortField = "txn_date_time"
    '    '        End Select
    '    '    End If

    '    'objConn.Open(DBConnectstring)
    '    With objCmd
    '        .Connection = objConn
    '        .CommandText = "VIAKLIX_VIRTUAL_TERMINAL.SetVTSortField"
    '        '.Parameters.Add(new SqlParameter(delete(1))
    '        .Parameters.Add(New SqlParameter("@sortfield", SqlDbType.VarChar, 25)).Value = UCase(SortField)
    '        .Parameters.Add(New SqlParameter("@errormsg", SqlDbType.VarChar, 50)).Direction = ParameterDirection.Output
    '    End With
    '    objCmd.Connection.Open()
    '    objCmd.ExecuteNonQuery()
    '    '------------------------------------------------------------------------
    '    'Returns a message to the calling ASP page.
    '    '------------------------------------------------------------------------
    '    If Not IsNothing(objCmd.Parameters("errormsg").Value) Then

    '        'Debug.Print("Error Msg = " & objCmd.Parameters("errormsg" 
    '        ErrMsg = objCmd.Parameters("errormsg").Value

    '        objCmd = Nothing
    '        objConn.Close()
    '        objConn = Nothing
    '        Exit Sub
    '    End If
    '    '------------------------------------------------------------------------

    '    'Exit Sub

    '    'ErrorHandler:
    '    '        Call LogErrorEvent("AdminMerchant.SaveSortField")

    '    '        If Not objRs Is Nothing Then
    '    '            If objRs.State <> adStateClosed Then
    '    '                objRs.Close()
    '    '            End If

    '    '            objRs = Nothing
    '    '        End If

    '    '        If Not objConn Is Nothing Then
    '    '            If objConn.State <> adStateClosed Then
    '    '                objConn.Close()
    '    '            End If

    '    '            objConn = Nothing
    '    '        End If

    '    '        objCmd = Nothing
    '    '        Exit Sub
    'End Sub

    'Private Function GetDisplayCriteria() As DataSet
    '    'THIS FUNCTION RETRIEVES ALL OF THE MERCHANT'S SPECIFIED DISPLAY CRITERIA



    '    Dim objConn As SqlConnection
    '    Dim objCmd As SqlCommand
    '    Dim objRs As DataSet
    '    Dim strSQL As String
    '    Dim sqladp As SqlDataAdapter
    '    'objConn = CreateObject("ADODB.Connection")
    '    'objCmd = CreateObject("ADODB.Command")
    '    'objRs = CreateObject("ADODB.Recordset")

    '    'objConn.Open(DBConnectstring)
    '    objCmd = New SqlCommand
    '    With objCmd
    '        '.Connection = objConn
    '        .CommandText = "VIAKLIX_VIRTUAL_TERMINAL.GetVTSession"
    '        .CommandType = CommandType.StoredProcedure
    '        .Parameters.Add(New SqlParameter("@sessionid", SqlDbType.VarChar, 40)).Value = SessionID
    '        .Parameters.Add(New SqlParameter("@errormsg", SqlDbType.VarChar, 50)).Direction = ParameterDirection.Output
    '    End With
    '    'sqladp.SelectCommand.CommandType = CommandType.StoredProcedure
    '    'sqladp.Fill(objRs, "GetVTSession")
    '    'With objRs
    '    '    .CursorType = adOpenStatic
    '    '    .CursorLocation = adUseClient
    '    'End With

    '    'objRs = objCmd.Execute

    '    '------------------------------------------------------------------------
    '    'Returns a message to the calling ASP page.
    '    '------------------------------------------------------------------------
    '    If Not IsNothing(objCmd.Parameters("errormsg").Value) Then
    '        'objRs = Nothing

    '        'Debug.Print("Error Msg = " & objCmd.Parameters("errormsg" 
    '        ErrMsg = objCmd.Parameters("errormsg").Value

    '        objCmd = Nothing
    '        objConn.Close()
    '        objConn = Nothing

    '    End If
    '    '------------------------------------------------------------------------

    '    'objCmd.ActiveConnection = Nothing
    '    'GetDisplayCriteria = objRs
    '    objCmd = Nothing



    '    'ErrorHandler:
    '    '        Call LogErrorEvent("BatchManager.GetDisplayCriteria")
    '    '        'objConn.Close
    '    '        'Set objConn = Nothing

    '    '        If Not objRs Is Nothing Then
    '    '            If objRs.State <> adStateClosed Then
    '    '                objRs.Close()
    '    '            End If

    '    '            objRs = Nothing
    '    '        End If

    '    '        If Not objConn Is Nothing Then
    '    '            If objConn.State <> adStateClosed Then
    '    '                objConn.Close()
    '    '            End If

    '    '            objConn = Nothing
    '    '        End If

    '    '        objCmd = Nothing
    'End Function

    Private Sub SaveCurrentPage()

        Dim objConn As SqlConnection
        Dim objCmd As SqlCommand

        objCmd = New SqlCommand

        'With objCmd
        '    .Connection = objConn
        '    .CommandText = "VIAKLIX_VIRTUAL_TERMINAL.SetVTPage"
        '    .CommandType = CommandType.StoredProcedure
        '    .Parameters.Add(New SqlParameter("@sessionid", SqlDbType.VarChar, 40)).Value = SessionID
        '    .Parameters.Add(New SqlParameter("@page", SqlDbType.Int, 100)).Value = nPage
        '    .Parameters.Add(New SqlParameter("@errormsg", SqlDbType.VarChar, 50)).Direction = ParameterDirection.Output
        'End With

        '------------------------------------------------------------------------
        'Returns a message to the calling ASP page.
        '------------------------------------------------------------------------
        If Not IsNothing(objCmd.Parameters("errormsg").Value) Then

            'Debug.Print("Error Msg = " & objCmd.Parameters("errormsg" 
            ErrMsg = objCmd.Parameters("errormsg").Value

            objCmd = Nothing
            'objConn.Close()
            objConn = Nothing
            Exit Sub
        End If
        '------------------------------------------------------------------------

        'End With
        'objCmd.ActiveConnection = Nothing
        'objConn.Close()
        'objConn = Nothing

        Exit Sub

        'ErrorHandler:
        '        Call LogErrorEvent("BatchManager.SaveCurrentPage")

        '        If Not objConn Is Nothing Then
        '            If objConn.State <> adStateClosed Then
        '                objConn.Close()
        '            End If

        '            objConn = Nothing
        '        End If

        '        objCmd = Nothing
    End Sub
    'Private Sub SetCurrentPage()
    '    Dim objRs As New DataSet
    '    Dim StoredPage As Integer

    '    objRs = GetDisplayCriteria()

    '    StoredPage = CInt(objRs.Tables(0).Rows(0).Item(7))


    '    SaveCurrentPage()

    '    Exit Sub
    'End Sub
    'Private Sub SaveSortOrder(ByVal Order As String)

    '    Dim objConn As SqlConnection
    '    Dim objCmd As SqlCommand
    '    Dim objRs As DataSet
    '    Dim strSQL As String
    '    Dim StoredOrder As String
    '    Dim SortOrder As String
    '    Dim UpdateOrder As Boolean
    '    Dim BatchSearch As Boolean
    '    Dim sqladp As SqlDataAdapter
    '    'objConn = CreateObject("adodb.Connection")
    '    'objCmd = CreateObject("adodb.Command")
    '    'objRs = CreateObject("adodb.Recordset")
    '    BatchSearch = False
    '    UpdateOrder = False

    '    'objConn.Open(DBConnectstring)
    '    objCmd = New SqlCommand
    '    With objCmd
    '        .Connection = objConn
    '        .CommandText = "VIAKLIX_VIRTUAL_TERMINAL.GetVTSortCriteria"
    '        .CommandType = CommandType.StoredProcedure
    '        .Parameters.Add(New SqlParameter("@sessionid", SqlDbType.VarChar, 40)).Value = SessionID
    '        .Parameters.Add(New SqlParameter("@errormsg", SqlDbType.VarChar, 50)).Direction = ParameterDirection.Output
    '    End With
    '    sqladp.SelectCommand.CommandType = CommandType.StoredProcedure
    '    sqladp.Fill(objRs, "GetVTSortCriteria")
    '    'With objRs
    '    '    .CursorType = adOpenStatic
    '    '    .CursorLocation = adUseClient
    '    'End With

    '    'objRs = objCmd.Execute

    '    '------------------------------------------------------------------------
    '    'Returns a message to the calling ASP page.
    '    '------------------------------------------------------------------------
    '    If Not IsNothing(objCmd.Parameters("errormsg").Value) Then
    '        'objRs = Nothing

    '        'Debug.Print("Error Msg = " & objCmd.Parameters("errormsg" 
    '        ErrMsg = objCmd.Parameters("errormsg").Value

    '        objCmd = Nothing
    '        objConn.Close()
    '        objConn = Nothing
    '        Exit Sub
    '    End If
    '    '------------------------------------------------------------------------

    '    StoredOrder = SafeString(objRs.Tables(0).Rows(0).Item(1))
    '    'objCmd.ActiveConnection = Nothing
    '    'objConn.Close()

    '    If StoredOrder <> Order Then
    '        UpdateOrder = True
    '        SortOrder = Order
    '    End If

    '    If UpdateOrder Then
    '        'objConn.Open(DBConnectstring)
    '        With objCmd
    '            .Connection = objConn
    '            .CommandText = "VIAKLIX_VIRTUAL_TERMINAL.SetVTSortOrder"
    '            '.Parameters.Delete(1)
    '            .Parameters.Add(New SqlParameter("@sortorder", SqlDbType.VarChar, 4)).Value = Order
    '            .Parameters.Add(New SqlParameter("@batch_search", SqlDbType.VarChar, 5)).Value = BatchSearch
    '            .Parameters.Add(New SqlParameter("@errormsg", SqlDbType.VarChar, 50)).Direction = ParameterDirection.Output
    '        End With
    '        objCmd.Connection.Open()
    '        objCmd.ExecuteNonQuery()
    '        '------------------------------------------------------------------------
    '        'Returns a message to the calling ASP page.
    '        '------------------------------------------------------------------------
    '        If Not IsNothing(objCmd.Parameters("errormsg").Value) Then

    '            'Debug.Print("Error Msg = " & objCmd.Parameters("errormsg" 
    '            ErrMsg = objCmd.Parameters("errormsg").Value

    '            objCmd = Nothing
    '            objConn.Close()
    '            objConn = Nothing
    '            Exit Sub
    '        End If
    '        '------------------------------------------------------------------------


    '        'objCmd.ActiveConnection = Nothing
    '        'objConn.Close()
    '        'objConn = Nothing

    '    End If

    '    Exit Sub

    '    'ErrorHandler:
    '    '        Call LogErrorEvent("BatchManager.SaveSortOrder")

    '    '        If Not objRs Is Nothing Then
    '    '            If objRs.State <> adStateClosed Then
    '    '                objRs.Close()
    '    '            End If

    '    '            objRs = Nothing
    '    '        End If

    '    '        If Not objConn Is Nothing Then
    '    '            If objConn.State <> adStateClosed Then
    '    '                objConn.Close()
    '    '            End If

    '    '            objConn = Nothing
    '    '        End If

    '    '        objCmd = Nothing

    '    'Exit Sub
    'End Sub

End Class
